#include "DataSender.h"
#include <QDebug>
#include <QMutexLocker>

DataSender::DataSender(QObject *parent)
    : QObject(parent), m_destPort(0)
{
}

void DataSender::setDestination(const QString &ip, quint16 port)
{
    QMutexLocker locker(&m_mutex);
    m_destAddress.setAddress(ip);
    m_destPort = port;
}

void DataSender::setDestination(const QHostAddress &address, quint16 port)
{
    QMutexLocker locker(&m_mutex);
    m_destAddress = address;
    m_destPort = port;
}

void DataSender::sendData(const QByteArray &data)
{
    QMutexLocker locker(&m_mutex);
    
    if (m_destPort == 0 || m_destAddress.isNull()) {
        emit errorOccurred("未设置目标地址和端口");
        return;
    }
    
    if (data.isEmpty()) {
        return; // 忽略空数据
    }
    
    // 发送数据
    qint64 bytesSent = m_socket.writeDatagram(data, m_destAddress, m_destPort);
    if (bytesSent != data.size()) {
        emit errorOccurred(QString("发送数据失败: %1").arg(m_socket.errorString()));
    } else {
        // 可选：仅在调试时输出
        // qDebug() << "发送数据:" << bytesSent << "字节";
    }
}
